<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2018/11/8
 * Time: 17:32
 */

namespace common\services;

use Yii;
use common\services\tool\ToolHttp;

use common\models\news\News;
use common\models\history\History;
use common\models\exchangeRate\ExchangeRate;


class JuHeDataService
{
    public function __construct()
    {
        $this->config = Yii::$app->params['juHe'];
        $this->calendarKey      = $this->config['calendar']['appKey'];       // TODO 万年历-日
        $this->lotteryKey       = $this->config['lottery']['appKey'];        // TODO 彩票
        $this->newsKey          = $this->config['news']['appKey'];           // TODO 新闻
        $this->exchangeRateKey  = $this->config['exchangeRate']['appKey'];   // TODO 汇率
        $this->historyKey       = $this->config['history']['appKey'];        // TODO 历史上的今天
    }

    /**
     * 获取新闻数据
     * @param string $type  top(头条，默认)
     *                      shehui(社会)
     *                      guonei(国内)
     *                      guoji(国际)
     *                      yule(娱乐)
     *                      tiyu(体育)
     *                      junshi(军事)
     *                      keji(科技)
     *                      caijing(财经)
     *                      shishang(时尚)
     * @return bool
     */
    public function getNewsHotspot($type = 'top')
    {
        $url = $this->config['news']['url'];
        $params = [
            'type' => $type,
            'key'  => $this->newsKey
        ];
        $result = $this->httpRequest($url, $params);
        if ($result && !empty($result['result']) && !empty($result['result']['data'])) {
            return $result['result']['data'];
        } else {
            return [];
        }
    }

    /**
     * 新闻入库
     * @param $result
     * @return array|bool|\yii\db\ActiveRecord[]
     */
    public function saveNewsHotspot($result)
    {
        if (empty($result) || !is_array($result)) {
            $date = date("Y-m-d H", strtotime("-1 hour")) . ":00:00";
            return $this->findNewsHotspot($date);
        }
        foreach ($result as $value) {
            $date = date('Y-m-d H:i:s');
            $newsModel = new News();
            $newsModel->title           =       $value['title'];
            $newsModel->date            =       date('Y-m-d H', strtotime($date)) . ':00:00';
            $newsModel->author_name     =       $value['author_name'];
            $newsModel->url             =       $value['url'];
            $newsModel->thumbnail_pic_s =       $value['thumbnail_pic_s'];
            $newsModel->save();
        }
        return News::find()
            ->select('title, date, author_name, url, thumbnail_pic_s')
            ->where(['date' => date('Y-m-d H') . ':00:00'])->asArray()->all();
    }

    /**
     * 查询当前时间节点数据库记录的新闻数据
     * @param $date
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findNewsHotspot($date = '')
    {
        if (empty($date)) {
            $date = date('Y-m-d H') . ':00:00';
        }
        return News::find()
            ->select('title, date, author_name, url, thumbnail_pic_s')
            ->where(['date' => $date])->asArray()->all();
    }

    /**
     * 获取汇率数据
     * @return array
     */
    public function getExchangeRate()
    {
        $url = $this->config['exchangeRate']['url'];
        $params = [
            'key'  => $this->exchangeRateKey
        ];
        $result = $this->httpRequest($url, $params);
        if ($result && !empty($result['result']) && !empty($result['result']['list'])) {
            return $result['result']['list'];
        } else {
            return [];
        }
    }

    /**
     * 汇率入库
     * @param $result
     * @return array|bool|\yii\db\ActiveRecord[]
     */
    public function saveExchangeRate($result)
    {
        if (empty($result) || !is_array($result)) {
            $date = date("Y-m-d H", strtotime("-1 hour")) . ":00:00";
            return $this->findExchangeRate($date);
        }
        foreach ($result as $value) {
            $model = ExchangeRate::find()->where(['currency' => $value[0]])->limit(1)->one();
            if (empty($model)) {
                $model = new ExchangeRate();
            }
            $model->date                    = date('Y-m-d H') . ':00:00';
            $model->currency                = $value[0];
            $model->company                 = $value[1];
            $model->buying_rate             = $value[2];
            $model->buying_price_of_cash    = $value[3];
            $model->selling_price_of_cash   = $value[4];
            $model->bank_converted_price    = $value[5];
            $model->save();
        }
        return ExchangeRate::find()->where(['date' => date('Y-m-d H') . ':00:00'])
            ->select('date, currency, company, buying_rate, buying_price_of_cash, selling_price_of_cash, bank_converted_price')
            ->asArray()->all();
    }

    /**
     * 查询当前时间节点数据库汇率数据
     * @param $date
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findExchangeRate($date = '')
    {
        if (empty($date)) {
            $date = date('Y-m-d H') . ':00:00';
        }
        return ExchangeRate::find()->where(['date' => $date])
            ->select('date, currency, company, buying_rate, buying_price_of_cash, selling_price_of_cash, bank_converted_price')
            ->asArray()->all();
    }

    /**
     * 获取历史上的今天
     * @return array
     */
    public function getHistory()
    {
        $url = $this->config['history']['url'];
        $params = [
            'key'   => $this->historyKey,
            'v'     => '1.0',
            'month' => date('m'),
            'day'   => date('d'),
        ];
        $result = $this->httpRequest($url, $params);
        if ($result && !empty(['result'])) {
            return $result['result'];
        } else {
            return [];
        }
    }

    /**
     * 历史上的今天入库
     * @param $result
     * @return array|\yii\db\ActiveRecord[]
     */
    public function saveHistory($result)
    {
        if (empty($result) || !is_array($result)) {
            $date = date('m-d', strtotime("-1 day"));
            return $this->findHistory($date);
        }
        foreach ($result as $value) {
            $model = History::find()->where(['h_id' => $value['_id']])->limit(1)->one();
            if (empty($model)) {
                $model = new History();
                $model->h_id    = $value['_id'];
                $model->title   = $value['title'];
                $model->pic     = $value['pic'];
                $model->year    = $value['year'];
                $model->month   = $value['month'];
                $model->day     = $value['day'];
                $model->date    = date('m-d');
                $model->des     = $value['des'];
                $model->lunar   = $value['lunar'];
                $model->save();
            }
        }
        return History::find()
            ->select('title, des, lunar, year, month, day, pic')
            ->where(['date' => date('m-d')])->orderBy('year DESC')
            ->asArray()->all();
    }

    /**
     * 查询历史上今天的数据
     * @param $date
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findHistory($date = '')
    {
        if (empty($date)) {
            $date = date('m-d');
        }
        return History::find()
            ->select('title, des, lunar, year, month, day, pic')
            ->where(['date' => $date])->orderBy('year DESC')
            ->asArray()->all();
    }




    /****************************************************************/

    /**
     * 万年历日数据-日数据
     *
     * @param string $date
     * @return bool
     */
    public function calendarDay($date = '')
    {
        // 接口地址
        $url = $this->config['calendar']['url'] . '/day';
        if (empty($date)) {
            $years = date('Y');
            $month = date('m') >= 10 ? date('m') : substr(date('m'), 1, 1);
            $day = date('d') >= 10 ? date('d') : substr(date('d'), 1, 1);
            $date = $years . '-' . $month . '-' . $day;
        }
        $params = array(
            "date" => $date,                    // 指定日期,格式为YYYY-MM-DD,如月份和日期小于10,则取个位,如:2012-1-1
            "key" => $this->calendarKey,    // 您申请的appKey
        );
        $result = $this->httpRequest($url, $params);
        if ($result) {
            if ($result['error_code'] == '0') {
                var_dump($result);
            } else {
                echo $result['error_code'] . ":" . $result['reason'];
            }
        } else {
            return false;
        }
    }

    /**
     * 万年历数据-月数据
     *
     * @param string $date
     * @return bool
     */
    public function calendarMonth($date = '')
    {
        // 接口地址
        $url = $this->config['calendar']['url'] . '/month';
        if (empty($date)) {
            $years = date('Y');
            $month = date('m') >= 10 ? date('m') : substr(date('m'), 1, 1);
            $date = $years . '-' . $month;
        }
        $params = array(
            "key" => $this->calendarKey, // 您申请的appKey
            "year-month" => $date,                   // 指定日期,格式为YYYY-MM,如月份小于10,则取个位,如:2012-1
        );
        $result = $this->httpRequest($url, $params);
        if ($result) {
            if ($result['error_code'] == '0') {
                var_dump($result);
            } else {
                echo $result['error_code'] . ":" . $result['reason'];
            }
        } else {
            return false;
        }
    }


    /**
     * 获取支持彩票列表
     * @return bool
     */
    public function getLotteryTypes()
    {
        $url = $this->config['lottery']['url'] . '/types';
        $params = [
            'key' => $this->lotteryKey
        ];
        $result = $this->httpRequest($url, $params);
        if ($result) {
            var_dump($result);
        } else {
            return false;
        }
    }

    /**
     * 获取彩票某一期开奖结果,默认最新一期
     *
     * @param $lotteryId 彩票ID
     * @param string $lotteryNo 彩票期数，默认最新一期
     * @return bool|mixed
     */
    public function getLotteryRes($lotteryId, $lotteryNo = "")
    {
        $url = $this->config['lottery']['url'] . '/query';
        $params = [
            'key' => $this->lotteryKey,
            'lottery_id' => $lotteryId,
            'lottery_no' => $lotteryNo
        ];
        $result = $this->httpRequest($url, $params);
        if ($result) {
            var_dump($result);
        } else {
            return false;
        }
    }

    /**
     * 获取历史开奖结果
     *
     * @param $lotteryId        彩票ID
     * @param int $pageSize     每页返回条数(最多也就一次获取50条)
     * @param int $page         当前页数
     * @return bool
     */
    public function getLotteryHistroyRes($lotteryId, $pageSize = 50, $page = 1)
    {
        $url = $this->config['lottery']['url'] . '/history';
        $params = [
            'key'        => $this->lotteryKey,
            'lottery_id' => $lotteryId,
            'page_size'  => $pageSize,
            'page'       => $page,
        ];
        $result = $this->httpRequest($url, $params);
        if ($result) {
            var_dump($result['result']['lotteryResList']);
        } else {
            return false;
        }
    }

    /**
     * 发起HTTP请求
     * @param $url
     * @param $params
     * @return mixed
     */
    public function httpRequest($url, $params)
    {
        $paramString = http_build_query($params);
        $content = ToolHttp::JuHeHttpCurl($url, $paramString);
        $result = json_decode($content, true);
        return $result;
    }
}